import requests
import pymysql


def get_car_rank_data(offset):
    """
    获取汽车排行榜数据
    """
    headers = {
        "accept": "*/*",
        "accept-language": "zh-CN,zh;q=0.9",
        "cache-control": "no-cache",
        "pragma": "no-cache",
        "priority": "u=1, i",
        "referer": "https://www.dongchedi.com/sales",
        "sec-ch-ua": "\"Google Chrome\";v=\"135\", \"Not-A.Brand\";v=\"8\", \"Chromium\";v=\"135\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36"
    }
    cookies = {
        "ttwid": "1%7C_-nwJL92ImJvbwRRekBpuiKkD2Qs2VCsVPpFF08ktes%7C1745933993%7C8f9e2c443469ba5ad20d17759c07c3e006059a2e375d844f7dd3d1929514805f",
        "tt_webid": "7498729296833054232",
        "tt_web_version": "new",
        "is_dev": "false",
        "is_boe": "false",
        "x-web-secsdk-uid": "122001fb-54c5-4036-953e-08c7de82829e",
        "Hm_lvt_3e79ab9e4da287b5752d8048743b95e6": "1745933995",
        "HMACCOUNT": "18EE3EC45AB48A04",
        "_gid": "GA1.2.1233820395.1745933996",
        "s_v_web_id": "verify_ma2k0suv_Y9HODyGa_MsB2_4Ziv_8TWj_zesNnGQu5SOL",
        "city_name": "%E6%88%90%E9%83%BD",
        "_ga_YB3EWSDTGF": "GS1.1.1745933996.1.1.1745934504.16.0.0",
        "_ga": "GA1.1.1039754764.1745933996",
        "Hm_lpvt_3e79ab9e4da287b5752d8048743b95e6": "1745934505"
    }
    url = "https://www.dongchedi.com/motor/pc/car/rank_data"
    params = {
        "aid": "1839",
        "app_name": "auto_web_pc",
        "city_name": "成都",
        "count": "10",
        "offset": str(offset),
        "month": "",
        "new_energy_type": "",
        "rank_data_type": "11",
        "brand_id": "",
        "price": "",
        "manufacturer": "",
        "series_type": "",
        "nation": "0"
    }
    response = requests.get(url, headers=headers, cookies=cookies, params=params)
    result = (response.json())
    for item in result["data"]["list"]:
        print(item)
        save_to_mysql(item)


def get_connection():
    return pymysql.connect(
        host='localhost',
        user='root',
        password='root',
        database='car_rank',
        charset='utf8mb4'
    )


def save_to_mysql(item):
    connection = get_connection()
    try:
        with connection.cursor() as cursor:
            sql = """
                REPLACE INTO car_rank (
                    series_id, series_name, image, ranks, min_price, max_price, last_rank, count, score,
                    car_review_count, show_trend, descender_price, series_pic_count,
                    brand_id, brand_name, sub_brand_id, sub_brand_name,
                    price, dealer_price, has_dealer_price
                ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
            """
            cursor.execute(sql, (
                item['series_id'],
                item['series_name'],
                item['image'],
                item['rank'],
                item['min_price'],
                item['max_price'],
                item['last_rank'],
                item['count'],
                item['score'],
                item['car_review_count'],
                item['show_trend'],
                item['descender_price'],
                item['series_pic_count'],
                item['brand_id'],
                item['brand_name'],
                item['sub_brand_id'],
                item['sub_brand_name'],
                item['price'],
                item['dealer_price'],
                item['has_dealer_price']
            ))
        connection.commit()
        print("数据保存成功")
    except Exception as e:
        print(e)
    finally:
        connection.close()


if __name__ == '__main__':
    for i in range(0, 200, 10):
        get_car_rank_data(i)
